package com.netty.netty.low.demo4;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;

public class NettyClient {

  public static void main(String[] args) {

      NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
      ChannelFuture channelFuture = new Bootstrap()
              .group(eventLoopGroup)
              .channel(NioSocketChannel.class)
              .handler(new ChannelInitializer<Channel>() {
                  @Override
                  protected void initChannel(Channel ch) throws Exception {

                      ch.pipeline().addLast(new StringEncoder());
                      ch.pipeline().addLast(new LoggingHandler());

                      ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){

                          @Override
                          public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                              System.out.println("--------------"+msg.toString());
                              super.channelRead(ctx, msg);
                          }
                      });

                  }
              }).connect("localhost", 8080);

      channelFuture.addListener(new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {

              Channel channel = future.channel();
              channel.writeAndFlush("client-----");
//              channel.close();
//              ChannelFuture closeFuture = channel.closeFuture();
//              closeFuture.addListener(new ChannelFutureListener() {
//                  @Override
//                  public void operationComplete(ChannelFuture future) throws Exception {
//                      eventLoopGroup.shutdownGracefully();
//                  }
//              });
          }
      });




  }
}
